package com.wzy.common.base.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/3/19 10:28
 * 4
 */
public class JacksonUtil {
    private static final Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static <T>List<T> string2List(Class<T> clazz, String str) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz);
        List<T> list = null;
        try {
            list = objectMapper.readValue(str, javaType);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            logger.error("string to List发生错误");
        }
        return list;
    }

    public static <T>String clazz2String(T t) {
        try {
            return objectMapper.writeValueAsString(t);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Map<String, Object> string2Map(String t) {
        try {
            return objectMapper.readValue(t, Map.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


}
